package com.agynamix.scala.mi

import _root_.java.io.File
import _root_.javax.script.ScriptException

/**
 * Created by IntelliJ IDEA.
 * User: tuhlmann
 * Date: 05.04.2010
 * Time: 19:01:26
 * To change this template use File | Settings | File Templates.
 */

class ITunesMediaProcessor extends MediaFileProcessor {

  def process(mediaFile: File): ITunesProcessResult = {
    val appleFileName = mediaFile.getAbsolutePath(); // .replace('/', ':');
    println("Found: " + appleFileName);

    try {
      return addMediaToItunes(appleFileName);
    } catch {
      case e => println("Could not import media file: "+appleFileName+", Error: "+e.getMessage)
                return new ITunesProcessResult(false, "") 
    }
  }

  @throws(classOf[ScriptException])
  def addMediaToItunes(appleFileName: String): ITunesProcessResult = {
    val sb = new StringBuilder();
    sb.append("set iTunesFile to POSIX file \"" + appleFileName + "\"\n");
    sb.append("tell application \"iTunes\"\n");
    sb.append("copy (add iTunesFile) to newMovie\n");
    sb.append("set pid to newMovie's persistent ID\n")
    sb.append("end tell");

    new ITunesProcessResult(true, scriptEngine.eval(sb.toString()).toString)
  }

}